<template>
  <div class="import_ship_cntr">
    <div class="top">
      <div class="EDI">
        <div class="title">
          EDI航次信息
        </div>
        <el-form inline :model="formInline" class="demo-form-inline">
          <el-form-item label="系统船名">
            <Select 
              :selectTableColumnData="selectTableColumnData" 
              :selectDefaultLabel ="formInline.ediXtcm" 
              placeholder="选择系统船名" 
              :disabled="!yzFinished"
              :selectTableData="ediData"
              optionKey="id" 
              @changeFdata="changeFdata(arguments,0)"
              :hasRemoteMethod="true"
              paramsKey="condition"
              url="/tos/tediship/getTEdiShipCntrMRpic"
              method='GET'
              :params="{condition:''}"
            />
          </el-form-item>
          <el-form-item label="航次">
            <el-card class="box-card">
              <span>{{formInline.hc}}</span>
            </el-card>
          </el-form-item>
          <el-form-item label="报文名">
            <el-card class="box-card" style="width:15vw">
              <span>{{formInline.bwm}}</span>
            </el-card>
          </el-form-item>
        </el-form>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">  
          <div>
            <el-form-item>
              <DiySearch 
                url="/tos/tediship/Query" 
                zdyUrl="/tos/tediship/selectShipDropList"
                :id="formInline.ediXtcm" 
                :tableColumnData="tableColumnData" 
                :tableData="tableData"
                @changeFdata="changeFdata(arguments,2)"
              />
            </el-form-item>
            <el-form-item>
              <el-button plain @click="getEdiJx(formInline.ediXtcm)">查询全部</el-button>
            </el-form-item>
            <el-form-item>
              <el-upload
                action=""
                class="upload-demo"
                multiple
                :show-file-list="false"
                :http-request="upload"
                :before-upload="beforeAvatarUpload"
              >
                <el-button size="small" type="primary">上传</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传txt文件</div> -->
              </el-upload>
            </el-form-item>
          </div>
          <div>
            <el-form-item>
              <el-button type="primary" @click="handleAdd">新增</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" @click="handleDelete">删除</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveEdiJx" :disabled="!getIsEdited">保存</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="downloadError" :disabled="errorData.length===0">下载错误数据</el-button>
            </el-form-item>
          </div>
          
        </el-form>
      </div>
      <div class="XT">
        <div class="title">
          系统航次信息
        </div>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="系统船名">
            <Select 
            :selectTableColumnData="selectTableColumnData1" 
            :selectDefaultLabel ="formInline.xtXtcm" 
            placeholder="选择系统船名" 
            :selectTableData="xtData" 
            optionKey="shipNo" 
            @changeFdata="changeFdata(arguments,1)"
            :hasRemoteMethod="true"
            paramsKey="condition"
            url="/tos/tediship/getVdeiShip"
            method='GET'
            :params="{condition:''}"/>
          </el-form-item>
          <el-form-item label="航次">
            <el-card class="box-card">
              <span>{{formInline.xthc}}</span>
            </el-card>
          </el-form-item>
          <el-form-item label="船代码">
            <el-card class="box-card">
              <span>{{formInline.cdm}}</span>
            </el-card>
          </el-form-item>
          <el-form-item label="内外贸">
            <el-card class="box-card">
              <span>{{formInline.nwm}}</span>
            </el-card>
          </el-form-item>
          
        </el-form>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="验证选项">
            <el-col :span="20">
              <el-checkbox-group v-model="formInline.yzxx">
                <el-checkbox label="空残损" name="yzxx"></el-checkbox>
                <el-checkbox label="贝位有箱" name="yzxx"></el-checkbox>
              </el-checkbox-group>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="handleYz" :disabled="getIsEdited || !yzFinished">验证</el-button>
            </el-col>
          </el-form-item>
          <el-form-item label="导入模式">
              <el-radio-group v-model="formInline.drms">
              <el-radio label="追加"></el-radio>
              <el-radio label="覆盖"></el-radio>
              <el-radio label="删除"></el-radio>
              <el-radio label="清空"></el-radio>
              <el-checkbox v-model="formInline.checked">不导过港箱</el-checkbox>
              <el-button type="primary" @click="handleDr" :disabled="errorData.length !== 0 || getIsEdited || !hasYz">导入</el-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="bottom">
      <div class="list-view" ref="tableDiv">
        <div class="title">报文数据（{{tableData.length}}条）</div>
        <el-table
          :data="visibleData"
          style="width: 100%"
          :cell-class-name="tableCellClassName"
          @cell-dblclick="tabClick"
          ref="myTable"
          id="myTable"
          row-key="id"
          height="100%"
          class="jxtable"
          :row-style="{ height: itemHeight + 'px' }"
          @selection-change="handleSelectionChange"
          @select-all="selectAll"
        >
          <el-table-column
            type="selection"
            width="50"
            :reserve-selection="true"
          ></el-table-column>
          <el-table-column v-for="item in tableColumnData" :key="item.props" 
            :prop="item.props" 
            :label="item.label" 
            sortable 
            show-overflow-tooltip 
            :render-header="labelHead"
            :width="item.width"
          >
            <template slot-scope="scope">
              <el-input
                v-if="
                  scope.row.index === tabClickRowIndex &&
                    scope.column.index === tabClickColumnIndex
                "
                style="width:80%"
                v-model="scope.row[item.props]"
                size="mini"
                :maxlength="item.max"
                @blur="inputBlur"
              ></el-input>
              <span v-else style="margin-left: 10px">{{ scope.row[item.props] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="question">
        <div class="title">错误数据</div>
        <el-table :data="visibleErrorData" 
          style="width: 100%" 
          height="100%" 
          ref="myErrorTable"
          id="myErrorTable"
          row-key="c2"
          @selection-change="questionSelectChange"
          @select-all="selectAll"
          :row-style="{ height: itemHeight + 'px' }"
        >
          
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55">
          </el-table-column>
          <el-table-column prop="remarkTxt" label="备注" 
            width="300"
            sortable 
            show-overflow-tooltip 
            :render-header="labelHead">
          </el-table-column>
          <el-table-column prop="c2" label="箱号"
            sortable 
            show-overflow-tooltip 
            :render-header="labelHead">
          </el-table-column>
          <el-table-column prop="c3" label="贝位"
            sortable 
            show-overflow-tooltip 
            :render-header="labelHead">
          </el-table-column>
          <el-table-column prop="c4" label="箱型"
            sortable 
            show-overflow-tooltip 
            :render-header="labelHead">
          </el-table-column>
          <el-table-column prop="c5" label="卸货港"
            sortable 
            show-overflow-tooltip 
            :render-header="labelHead">
          </el-table-column>
          <el-table-column prop="c6" label="残损"
            sortable 
            show-overflow-tooltip 
            :render-header="labelHead">
          </el-table-column>
          
        </el-table>
      </div>
    </div>

  </div>
</template>

<script>
import api from '@/api/modules/EDI/index.js'
import Select from '@/components/Select/import-ship-cntr'
import DiySearch from '@/components/Select/diy-search'
import editPageLeavePrompt from '@/mixins/closeChrome.js'
import XLSX from 'xlsx'
export default {
  name: 'importShipCntr',
  components: { Select, DiySearch },
  mixins: [editPageLeavePrompt],
  data() {
    return {
      formInline: { // edi和系统船名 选定船名
        ediXtcm: '',
        xtXtcm: '',
        hc: '', // edi航次
        bwm: '', // edi报文名
        xthc: '', // 系统航次
        cdm: '', // 系统船代码
        nwm: '', // 系统内外贸
        yzxx: [], // 验证模式
        drms: '追加', // 导入模式
        checked: true // 不导过港箱
      },
      selectTableColumnData: [
        { label: '船名', props: 'shipNam', width: 200 },
        { label: '船航次', props: 'voyage', width: 90 },
        { label: '解析时间', props: 'recTim', width: 180 },
        { label: '报文名', props: 'fileName', width: 600 }
      ],
      selectTableColumnData1: [
        { label: '船名', props: 'shipNam', width: 100 },
        { label: '船编号', props: 'shipNo', width: 100 },
        { label: '船代码', props: 'shipCod', width: 90 },
        { label: '船航次', props: 'voyage', width: 90 },
        { label: '进出口', props: 'ieid', width: 90 },
        { label: '内外贸', props: 'tradeId', width: 90 }
      ],
      ediData: [], // edi航次信息
      xtData: [], // 系统航次信息
      tableData: [], // 附件解析信息
      visibleData: [], // 虚拟列表展示数据
      tableColumnData: [
        { label: '箱号', props: 'cntr', VO: 'CNTR', width: 150 },
        { label: '类型', props: 'cntrSizTyp', VO: 'CNTR_SIZ_TYP', max: '4' },
        { label: '尺寸', props: 'cntrSizCod', VO: 'CNTR_SIZ_COD', max: '2' },
        { label: '箱型', props: 'cntrTypCod', VO: 'CNTR_TYP_COD', max: '2' },
        { label: '空重', props: 'efid', VO: 'E_F_ID', max: '1' },
        { label: '贝位', props: 'stowLoc', VO: 'STOW_LOC', max: '7' },
        { label: '箱公司', props: 'cntrCorpCod', VO: 'CNTR_CORP_COD', max: '6' },
        { label: '箱毛重', props: 'cntrGrossWgt', VO: 'CNTR_GROSS_WGT' },
        { label: '提单号', props: 'billNo', VO: 'BILL_NO', width: 155 },
        { label: '装货港', props: 'loadPortCod', VO: 'LOAD_PORT_COD' },
        { label: '目的港', props: 'discPortCod', VO: 'DISC_PORT_COD', max: '5' },
        { label: '卸货地', props: 'delvPlacCod', VO: 'DELV_PLAC_COD', max: '5' },
        { label: '航线', props: 'tranPortCod', VO: 'TRAN_PORT_COD' },
        { label: '危险品', props: 'dangClass', VO: 'DANG_CLASS', max: '5' },
        { label: '危险品页号', props: 'dangPage', VO: 'DANG_PAGE' },
        { label: '联合国编号', props: 'undgNo', VO: 'UNDG_NO', max: '4' },
        { label: '湿度', props: 'humidity', VO: 'HUMIDITY' },
        { label: '温度单位', props: 'tempId', VO: 'TEMP_ID', max: '1' },
        { label: '温度设置', props: 'tempSet', VO: 'TEMP_SET', max: '5' },
        { label: '超高', props: 'overHit', VO: 'OVER_HIT', max: '4' },
        { label: '铅封号', props: 'cntrSealNo', VO: 'CNTR_SEAL_NO' },
        { label: '箱净重', props: 'cntrNetWgt', VO: 'CNTR_NET_WGT' },
        { label: '箱分类', props: 'cntrId', VO: 'CNTR_ID', max: '3' },
        { label: '拼箱', props: 'srcId', VO: 'SRC_ID', max: '1' },
        { label: '残损', props: 'cntrDam', VO: 'CNTR_DAM', max: '5' },
        { label: '折叠', props: 'foldId', VO: 'FOLD_ID', max: '1' },
        { label: '货物代码', props: 'cargoCod', VO: 'CARGO_COD', max: '6' },
        { label: '货物名称', props: 'cargoNam', VO: 'CARGO_NAM' },
        { label: '交货条款', props: 'delvTerm', VO: 'DELV_TERM', max: '9' },
        { label: '危险品标签', props: 'dangLabel', VO: 'DANG_LABEL' },
        { label: '危险货物闪亮', props: 'flashPoint', VO: 'FLASH_POINT' },
        { label: '应急措施号', props: 'emsNo', VO: 'EMS_NO', max: '6' },
        { label: '应急联系', props: 'emsContact', VO: 'EMS_CONTACT' },
        { label: '医疗急救指南号', props: 'mfagNo', VO: 'MFAG_NO', max: '4' },
        { label: '通风', props: 'ventilation', VO: 'VENTILATION', max: '10' },
        { label: '前超', props: 'overLenFront', VO: 'OVER_LEN_FRONT', max: '4' },
        { label: '后超', props: 'overLenBack', VO: 'OVER_LEN_BACK', max: '4' },
        { label: '左超', props: 'overWidLeft', VO: 'OVER_WID_LEFT', max: '4' },
        { label: '右超', props: 'overWidRight', VO: 'OVER_WID_RIGHT', max: '4' },
        { label: '船代码', props: 'shipCod', VO: 'SHIP_COD', max: '4' }
      ], // 附件解析表头信息
      errorData: [], // 问题信息
      visibleErrorData: [], // 虚拟列表问题信息
      getIsEdited: false, // 是否需要保存
      hasYz: false, // 是否验证
      yzFinished: true, // 是否完成验证过程
      tabClickRowIndex: null, // 点击行的index
      tabClickColumnIndex: null, // 点击列的index
      listQuery: {
        rwmc: '',
        fpr: '',
        pageNum: 1,
        pageSize: 20
      },
      enterNumber: 0,
      itemHeight: 50, // 行高
      multipleSelection: [], // 解析选中部分的list
      questionSelection: [], // 问题选中部分
      fileList: [],
      timer: ''
    };
  },
  watch: {
    'formInline.xtXtcm': {
      handler(newV, oldV) {
        let params = []
        this.xtData.forEach(item => {
          if (item.shipNo === newV) {
            params = item
          }
        })
        this.formInline.xtXtcm = newV
        this.formInline.xthc = params.voyage
        this.formInline.nwm = params.tradeId
        this.formInline.cdm = params.shipCod
        console.log('xt:', newV, oldV);
      },
      deep: true
    },
    'formInline.ediXtcm': {
      handler(newV, oldV) {
        // if (newV === undefined || newV === '') return
        let params = []
        this.ediData.forEach(item => {
          if (item.id === newV) {
            params = item
          }
        })
        console.log(this.ediData, newV, oldV, params, 'edidatrqa', this.enterNumber);
        this.formInline.ediXtcm = newV
        this.formInline.hc = params.voyage
        this.formInline.bwm = params.fileName
        if (oldV !== '' || this.enterNumber !== 0) { // 首次进入不调
          this.getEdiJx(newV)
          this.getEdiXtGl({ shipCode: params.shipCod, voyage: params.voyage })
        }
        this.enterNumber++
      },
      deep: true
    },
    tableData: {
      handler(newV, oldV) {
        console.log('newV:', newV, oldV);
        if (oldV.length > 0) {
          this.getIsEdited = true
        }
      },
      deep: true
    }
  },
  computed: {
    contentHeight() {
      return this.tableData.length * this.itemHeight + 'px';
    }
  },
  async created() {
    window.addEventListener('keydown', this.handleKeyDown, true); // 开启监听键盘按下事件
  },
  async mounted() {
    this.getXtHc()
    await this.getEdiHc()
    await this.getEdiJx(this.ediData[0].id)
    this.tableListener();
    this.updateVisible();
    document.getElementById('myTable').style.height = '99.99%' // 修改高度使其重新渲染
    // window.addEventListener('beforeunload', (event) => {
    //   // Cancel the event as stated by the standard.
    //   event.preventDefault();
    //   // Chrome requires returnValue to be set.
    //   event.returnValue = '';
    // });
  },
  activated() {
    const tableBody = document.getElementById('myTable').children[2];
    const errorTableBody = document.getElementById('myErrorTable').children[2];
    tableBody.scrollTop = sessionStorage.getItem('INSCROLL')
    errorTableBody.scrollTop = sessionStorage.getItem('ERRORINSCROLL')
    // 5分钟自动发送一次 5 * 60 * 1000
    // this.timer = setInterval(() => {
    //   this.getEdiHc().then(res => {
    //     this.getEdiJx(this.ediData[0].id)
    //   })
    // }, 5 * 60 * 1000);
  },
  deactivated() {
    // clearInterval(this.timer)
  },
  methods: {
    /**
     * 获取EDI航次数据
     */
    async getEdiHc() {
      const edihc = await api.reqGetEdihc({ condition: '' })
      this.ediData = edihc.data
      this.formInline.ediXtcm = this.ediData[0].id
      this.formInline.hc = this.ediData[0].shipCod
      this.formInline.bwm = this.ediData[0].fileName
      const params = { shipCode: this.ediData[0].shipCod, voyage: this.ediData[0].voyage }
      console.log(params, 'params');
      this.getEdiXtGl(params)
    },
    /**
     * 获取EDI和系统航次的关联关系
     */
    async getEdiXtGl(params) {
      const res = await api.reqGetEdiXt(params)
      console.log(res, 'res');
      if (res.data.length > 0) {
        this.formInline.xtXtcm = res.data[0].shipNo
        this.formInline.xthc = res.data[0].voyage
        this.formInline.nmw = res.data[0].tradeId
        this.formInline.cdm = res.data[0].shipCod
      } else {
        this.formInline.xtXtcm = ''
        this.formInline.xthc = ''
        this.formInline.nwm = ''
        this.formInline.cdm = ''
      }
    },
    /**
     * 根据航次获取解析信息
     */
    async getEdiJx(id) {
      const params = { id }
      const edijx = await api.reqGetEdiJx(params)
      this.tableData = edijx.data
      setTimeout(() => {
        this.getIsEdited = false
      }, 100);
      sessionStorage.setItem('TABLEDATA', JSON.stringify(this.tableData))
      this.errorData = []
      this.updateVisible();
      this.updateVisible(0, 'errorDom');
    },
    /**
     * 获取系统航次数据
     */
    async getXtHc() {
      const edihc = await api.reqGetXtHc()
      this.xtData = edihc.data
    },
    /**
     * 新增数据
     */
    handleAdd() {
      const newData = JSON.parse(JSON.stringify(this.tableData[this.tableData.length - 1]))
      newData.id = '-' + new Date().getTime()
      this.tableData.unshift(newData)
      this.visibleData.unshift(newData)
    },
    /**
     * 删除数据
     */
    async handleDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '未选择数据',
          type: 'warning'
        });
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let deleteData = []
          if (this.$refs.myTable.store.states.isAllSelected) {
            deleteData = this.tableData
          } else {
            deleteData = this.multipleSelection
          }
          api.reqDeleteJx(deleteData).then(res => {
            if (res.code === '00000000') {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            } else {
              this.$message({
                message: '删除失败',
                type: 'warning'
              });
            }
            this.$refs.myTable.store.states.selection = [] // 清空选定信息
            this.multipleSelection = []
            this.getEdiJx(this.formInline.ediXtcm)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    /**
     * 保存数据(修改数据)
     */
    async saveEdiJx() {
      console.log(this.tableData);
      const res = await api.reqSaveJx(this.tableData)
      if (res.code === '00000000') {
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        await this.getEdiJx(this.formInline.ediXtcm)
        this.getIsEdited = false
      } else {
        this.$message({
          message: '保存失败',
          type: 'warning'
        });
      }

      console.log(res, 'resss');
    },
    /**
     * 验证数据
     */
    async handleYz() {
      const ibTran = this.formInline.yzxx.indexOf('空残损') > -1 ? 'Y' : 'N'
      const ibDam = this.formInline.yzxx.indexOf('贝位有箱') > -1 ? 'Y' : 'N'
      const params = {
        idM: this.formInline.ediXtcm,
        id: this.formInline.ediXtcm,
        shipNo: this.formInline.xtXtcm,
        operNam: JSON.parse(sessionStorage.getItem('userInfo')).userName,
        ibTran,
        ibDam,
        llsG: this.formInline.checked ? 'Y' : 'N'
      }
      if (this.formInline.ediXtcm === '' || this.formInline.ediXtcm === undefined) {
        this.$message({
          message: '请选择EDI航次的系统船名',
          type: 'warning'
        });
      } else if (this.formInline.xtXtcm === '' || this.formInline.xtXtcm === undefined) {
        this.$message({
          message: '请选择系统航次的系统船名',
          type: 'warning'
        });
      } else {
        this.yzFinished = false
        await api.reqEdjYz(params)
        const res1 = await api.reqEdjYzz()
        if (res1.code === '00000000') {
          this.yzFinished = true // 完成验证
          this.hasYz = true // 是否验证过

          this.$message({
            message: '验证成功',
            type: 'success'
          });
        }
        this.errorData = res1.data.filter(item => item.createby === JSON.parse(sessionStorage.getItem('userInfo')).userName)
        this.updateVisible(0, 'errorDom');
      }
    },
    /**
     * 导入数据
     */
    async handleDr() {
      const ibTran = this.formInline.yzxx.indexOf('空残损') > -1 ? 'Y' : 'N'
      const ibDam = this.formInline.yzxx.indexOf('贝位有箱') > -1 ? 'Y' : 'N'
      let model = 'A'
      if (this.formInline.drms === '清空') {
        model = 'C'
      } else if (this.formInline.drms === '覆盖') {
        model = 'O'
      } else if (this.formInline.drms === '删除') {
        model = 'D'
      }
      const params = {
        id: this.formInline.ediXtcm,
        shipNo: this.formInline.xtXtcm,
        operNam: JSON.parse(sessionStorage.getItem('userInfo')).userName,
        ibTran,
        ibDam,
        model,
        llsG: this.formInline.checked ? 'Y' : 'N'
      }
      if (this.formInline.ediXtcm === '' || this.formInline.ediXtcm === undefined) {
        this.$message({
          message: '请选择EDI航次的系统船名',
          type: 'warning'
        });
      } else if (this.formInline.xtXtcm === '' || this.formInline.xtXtcm === undefined) {
        this.$message({
          message: '请选择系统航次的系统船名',
          type: 'warning'
        });
      } else {
        const res = await api.reqEdjDr(params)
        if (res.code === '00000000') {
          this.$message({
            message: '导入成功',
            type: 'success'
          });
        }
      }
    },
    /**
     * 上传
     */
    upload(file) {
      console.log(file, 'file')
      const formData = new FormData()
      formData.append('file', file.file)
      api.uploadD(formData).then(response => {
        if (response.code === '00000000') {
          this.$message({
            message: response.data,
            type: 'success'
          });
          this.getEdiHc().then(res => {
            this.getEdiJx(this.ediData[0].id)
          })
        }
      })
    },
    /**
     * 上传前的限制条件
     */
    beforeAvatarUpload(file) {
      console.log(file.type, 'ss');
      const isTXT = file.type === 'text/plain';
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isTXT) {
        this.$message.error('上传文件只能是 TXT 格式!');
      }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      // return isJPG && isLt2M;
      return isTXT
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex;
      column.index = columnIndex;
    },
    tabClick(row, column, cell, event) {
      console.log(cell.innerText);
      this.tabClickRowIndex = row.index;
      this.tabClickColumnIndex = column.index;
      console.log(this.tabClickColumnIndex, 'column');
    },
    // 失去焦点初始化
    inputBlur(row, event, column) {
      if (this.multipleSelection.length > 1) { // 处理多行批量修改
        const zd = this.tableColumnData[this.tabClickColumnIndex - 1].props
        this.multipleSelection.forEach(item => {
          this.tableData.forEach(i => {
            if (i.id === item.id) {
              i[zd] = this.tableData[this.tabClickRowIndex][zd]
            }
          })
          // this.tableData[item.index][zd] = this.tableData[this.tabClickRowIndex][zd]
        })
      }
      this.tabClickRowIndex = null;
      this.tabClickColumnIndex = null;
    },
    // enter键事件
    handleKeyDown(e) {
      let key = null;
      if (window.event === undefined) {
        key = e.keyCode;
      } else {
        key = window.event.keyCode;
      }
      if (key === 13) {
        this.inputBlur();
      }
    },
    /**
     * 更新视图渲染的数据
     */
    updateVisible(scrollTop, dom) {
      scrollTop = scrollTop || 0;
      dom = dom || 'dom';
      console.log(dom, 'dom');
      const visibleCount =
        Math.ceil(this.$refs.tableDiv.clientHeight / this.itemHeight) + 5; // 取得可见区域的可见列表项数量 = 可见高度 / 单个项目高度
      const start = Math.floor(scrollTop / this.itemHeight); // 取得可见区域的起始数据索引 = 滚动到上面的高度 / 单个项目高度
      const end = start + visibleCount; // 取得可见区域的结束数据索引
      // 报文数据虚拟列表数据赋值
      if (end > this.tableData.length && dom === 'dom') {
        this.visibleData = this.tableData.slice(start, this.tableData.length); // 计算出可见区域对应的数据，更新渲染数据
      } else if (end <= this.tableData.length && dom === 'dom') {
        console.log('11123');
        this.visibleData = this.tableData.slice(start, end); // 计算出可见区域对应的数据，更新渲染数据
      }
      // 错误数据虚拟列表数据赋值
      if (end > this.errorData.length && dom === 'errorDom') {
        this.visibleErrorData = this.errorData.slice(start, this.errorData.length); // 计算出可见区域对应的数据，更新渲染数据
      } else if (end <= this.errorData.length && dom === 'errorDom') {
        this.visibleErrorData = this.errorData.slice(start, end); // 计算出可见区域对应的数据，更新渲染数据
      }
      // 报文数据全选处理
      if (this.$refs.myTable.store.states.isAllSelected && dom === 'dom') {
        // 如果全选矿选中，则遍历所有新数据使其选中。
        this.visibleData.forEach(item => {
          this.$refs.myTable.toggleRowSelection(item, true);
        });
      }
      // 错误数据全选处理
      if (this.$refs.myErrorTable.store.states.isAllSelected && dom === 'errorDom') {
        // 如果全选矿选中，则遍历所有新数据使其选中。
        this.visibleErrorData.forEach(item => {
          this.$refs.myErrorTable.toggleRowSelection(item, true);
        });
      }

      if (dom === 'dom') { // 报文数据位移处理
        const tableBody = document.getElementById('myTable').children[2].firstElementChild;
        tableBody.style.webkitTransform = `translate3d(0, ${start *
        this.itemHeight}px, 0)`; // 把可见区域的 top 设置为起始元素在整个列表中的位置（使用 transform 是为了更好的性能）
      } else if (dom === 'errorDom') { // 错误数据位移处理
        const errorTableBody = document.getElementById('myErrorTable').children[2].firstElementChild;
        errorTableBody.style.webkitTransform = `translate3d(0, ${start *
        this.itemHeight}px, 0)`; // 把可见区域的 top 设置为起始元素在整个列表中的位置（使用 transform 是为了更好的性能）
      }
    },
    /**
     * table懒加载滚动事件
     */
    tableListener() {
      const that = this;
      const dom = that.$refs.myTable.bodyWrapper;
      const errorDom = that.$refs.myErrorTable.bodyWrapper;
      dom.addEventListener('scroll', function() {
        // 整合选中选项
        // const scrollDistance =
        //   dom.scrollHeight - dom.scrollTop - dom.clientHeight;
        // if (scrollDistance <= 0) {
        //   // 等于0证明已经到底，可以请求接口
        //   if (that.listQuery.pageNum < that.totalPage) {
        //     // 当前页数小于总页数就请求
        //     that.listQuery.pageNum++; // 当前页数自增
        //     // 请求接口的代码
        //     that.getList();
        //   }
        // }
        const scrollTop = dom.scrollTop;
        sessionStorage.setItem('INSCROLL', scrollTop) // 存储滚动高度
        if (that.questionSelection.length > 0) return
        that.updateVisible(scrollTop, 'dom');
      });
      errorDom.addEventListener('scroll', function() {
        const scrollTop = errorDom.scrollTop;
        sessionStorage.setItem('ERRORINSCROLL', scrollTop) // 存储滚动高度
        that.updateVisible(scrollTop, 'errorDom');
      });
    },
    // 选中修改
    handleSelectionChange(val) {
      // val.forEach(item => {
      //   if (this.multipleSelection.indexOf(item) < 0) {
      //     this.multipleSelection = this.multipleSelection.concat(item);
      //   }
      // });
      console.log(this.$refs.myTable.store.states, '???');
      this.multipleSelection = val
    },
    // 问题选中
    questionSelectChange(val) {
      this.questionSelection = val
      this.visibleData = [] // 先将显示数组置空
      if (val.length === 0) { // 如果未选中，则给到原始值
        this.updateVisible()
      } else {
        console.log(this.$refs.myErrorTable.store.states.isAllSelected, '123');
        this.questionSelection.forEach(item => {
          this.tableData.forEach(i => {
            if (i.cntr === item.c2) { this.visibleData.push(i) }
          })
        })
        const tableBody = document.getElementById('myTable').children[2].firstElementChild;
        tableBody.style.webkitTransform = `translate3d(0, 0, 0)`;
      }
    },
    // 全选
    selectAll(val) {
      if (!this.$refs.myTable.store.states.isAllSelected) {
        // 如果全选矿选中，则遍历所有新数据使其选中。
        // this.visibleData.forEach(item => {
        //   this.$refs.myTable.toggleRowSelection(item, false);
        // });
        this.$refs.myTable.store.states.selection = []
        this.multipleSelection = []
      }
      if (!this.$refs.myErrorTable.store.states.isAllSelected) {
        this.$refs.myErrorTable.store.states.selection = []
        this.questionSelection = []
      }
    },
    // 子组件修改本组件的方法
    changeFdata(text, index) {
      this.hasYz = false
      if (index === 0) {
        this.formInline.ediXtcm = text[0]
        console.log('xiugai');
      } else if (index === 1) {
        this.formInline.xtXtcm = text[0]
      } else if (index === 2) {
        this.tableData = text[0]
        this.updateVisible()
      }
    },
    // 表头不换行
    labelHead(h, { column, index }) {
      // 新建一个 span
      const span = document.createElement('span');
      // 设置表头名称
      span.innerText = column.label;
      // 临时插入 document
      document.body.appendChild(span);
      // 重点：获取 span 最小宽度，设置当前列，注意这里加了 20，字段较多时还是有挤压，且渲染后的 div 内左右 padding 都是 10，所以 +20 。（可能还有边距/边框等值，需要根据实际情况加上）
      column.minWidth = span.getBoundingClientRect().width + 50;
      // 移除 document 中临时的 span
      document.body.removeChild(span);
      return h('span', column.label);
    },
    // 生成excel的配置
    workbook2blob(workbook) {
      // 生成excel的配置项
      var wopts = {
        // 要生成的文件类型
        bookType: 'xlsx',
        // // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        bookSST: false,
        type: 'binary'
      }
      var wbout = XLSX.write(workbook, wopts)
      // 将字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
        return buf
      }
      const buf = s2ab(wbout)
      var blob = new Blob([buf], {
        type: 'application/octet-stream'
      })
      return blob
    },

    // 将blob对象 创建bloburl,然后用a标签实现弹出下载框
    openDownloadDialog(blob, fileName) {
      if (typeof blob === 'object' && blob instanceof Blob) {
        blob = URL.createObjectURL(blob) // 创建blob地址
      }
      var aLink = document.createElement('a')
      aLink.href = blob
      // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file:///模式下不会生效
      aLink.download = fileName || ''
      var event
      if (window.MouseEvent) event = new MouseEvent('click')
      //   移动端
      else {
        event = document.createEvent('MouseEvents')
        event.initMouseEvent(
          'click',
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        )
      }
      aLink.dispatchEvent(event)
    },

    // xlsx的按钮点击事件
    downloadError() {
      this.exportExcel()
    },

    // 生成excel数据
    exportExcel() {
      const data = []
      this.errorData.forEach(item => {
        const obj = { '备注': item.remarkTxt, '箱号': item.c2, '贝位': item.c3, '箱型': item.c4, '卸货港': item.c5, '残损': item.c6 }
        data.push(obj)
      })
      var sheet1 = XLSX.utils.json_to_sheet(data)
      // 创建一个新的空的workbook
      var wb = XLSX.utils.book_new()
      const userName = JSON.parse(sessionStorage.getItem('userInfo')).userName
      XLSX.utils.book_append_sheet(wb, sheet1, userName + '用户错误数据')
      const workbookBlob = this.workbook2blob(wb)
      this.openDownloadDialog(workbookBlob, userName + '用户错误数据.xls')
    }
  }
};
</script>

<style lang="less" scoped>
.import_ship_cntr {
  padding: 10px 20px;
  height: calc(100vh - 94px);
  .top {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 125px;
    .EDI,
    .XT {
      width: 49%;
      .title {
        font-size: 20px;
        font-weight: 600;
      }
      .box-card {
        width: 5vw;
        height: 30px;
        text-align: center;
      }
    }
  }
  .bottom {
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 94px - 185px);
    .list-view {
      // display: flex;
      position: relative;
      width: 59%;
      height: 100%;
      margin-top: 15px;
    }
    .question {
      width: 40%;
      height: 100%;
      margin-top: 15px;
    }
  }
  
}
.demo-form-inline {
  display: flex;
  justify-content: space-between;
}

.list-view::-webkit-scrollbar {
  width: 0 !important;
}
// 显示内容的盒子
.list-view-content {
  left: 0;
  right: 0;
  top: 0;
  position: absolute;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 10px;
  margin-top: 10px;
}

/deep/ .el-card__body {
  padding: 0px;
} 
// table里面的输入框
/deep/ .cell .el-input--mini .el-input__inner {
    padding: 0;
    text-align: center;
}
/deep/ .el-dialog__body {
    padding: 0px 20px;
}
/deep/ .el-dialog {
  width: 70vw!important;
}
// 单选框margin修改
/deep/ .el-radio {
  margin-right: 10px;
}
/deep/ .el-checkbox {
  margin-right: 10px;
}
.el-table {
  /deep/ .el-table__body-wrapper::-webkit-scrollbar {
    width: 10px; /*滚动条宽度*/
    height: 10px; /*滚动条高度*/
  }
  /*定义滚动条轨道 内阴影+圆角*/
  /deep/ .el-table__body-wrapper::-webkit-scrollbar-track {
    box-shadow: 0px 1px 3px rgba(214, 216, 221, 0) inset; /*滚动条的背景区域的内阴影*/
    border-radius: 10px; /*滚动条的背景区域的圆角*/
    background-color: rgba(214, 216, 221, 0); /*滚动条的背景颜色*/
  }
  /*定义滑块 内阴影+圆角*/
  /deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
    box-shadow: 0px 1px 3px rgba(214, 216, 221, 0) inset; /*滚动条的内阴影*/
    border-radius: 10px; /*滚动条的圆角*/
    background-color: rgba(0, 0, 0, 0.15); /*滚动条的背景颜色*/
  }
}
</style>
